package com.example.backed.controller;

import com.example.backed.dto.OrderCreateDTO;
import com.example.backed.dto.OrderQueryDTO;
import com.example.backed.entity.Order;
import com.example.backed.service.OrderService;
import com.example.backed.util.SecurityUtil;
import com.example.backed.vo.OrderStatsVO;
import com.example.backed.vo.PageVO;
import com.example.backed.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "订单管理")
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

    @Operation(summary = "创建订单")
    @PostMapping
    public Result<Order> createOrder(@Validated @RequestBody OrderCreateDTO createDTO) {
        Long userId = SecurityUtil.getCurrentUserId();
        Order order = orderService.createOrder(userId, createDTO);
        return Result.success(order);
    }

    @Operation(summary = "获取订单详情")
    @GetMapping("/{id}")
    public Result<Order> getOrderDetail(
            @Parameter(description = "订单ID") @PathVariable("id") Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        Order order = orderService.getOrderDetail(userId, id);
        return Result.success(order);
    }

    @Operation(summary = "获取用户订单列表")
    @GetMapping("/my")
    public Result<PageVO<Order>> getUserOrders(
            @Parameter(description = "订单状态：0-待支付，1-已支付，2-已发货，3-已完成，4-已取消") 
            @RequestParam(required = false) Integer status,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        Long userId = SecurityUtil.getCurrentUserId();
        OrderQueryDTO query = new OrderQueryDTO();
        query.setStatus(status);
        query.setPageNum(pageNum);
        query.setPageSize(pageSize);
        PageVO<Order> pageVO = orderService.getUserOrderList(userId, query);
        return Result.success(pageVO);
    }

    @Operation(summary = "取消订单")
    @PostMapping("/{id}/cancel")
    public Result<Boolean> cancelOrder(
            @Parameter(description = "订单ID") @PathVariable("id") Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        boolean success = orderService.cancelOrder(userId, id);
        return success ? Result.success(true) : Result.error("取消订单失败");
    }

    @Operation(summary = "删除订单")
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteOrder(
            @Parameter(description = "订单ID") @PathVariable("id") Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        boolean success = orderService.deleteOrder(userId, id);
        return success ? Result.success(true) : Result.error("删除订单失败");
    }

    @Operation(summary = "获取订单统计信息")
    @GetMapping("/stats")
    public Result<OrderStatsVO> getOrderStats() {
        OrderStatsVO stats = orderService.getOrderStats();
        return Result.success(stats);
    }

    /**
     * 根据订单编号获取订单
     */
    @GetMapping("/no/{orderNo}")
    public Result<Order> getOrderByOrderNo(@PathVariable String orderNo) {
        Order order = orderService.getOrderByOrderNo(orderNo);
        if (order == null) {
            return Result.error("订单不存在");
        }
        // 验证是否是当前用户的订单
        Long userId = SecurityUtil.getCurrentUserId();
        if (!order.getUserId().equals(userId)) {
            return Result.error("无权查看此订单");
        }
        return Result.success(order);
    }

    /**
     * 获取当前用户的订单列表
     */
    @GetMapping("/list")
    public Result<PageVO<Order>> getMyOrders(OrderQueryDTO query) {
        Long userId = SecurityUtil.getCurrentUserId();
        PageVO<Order> pageVO = orderService.getUserOrderList(userId, query);
        return Result.success(pageVO);
    }

    /**
     * 获取所有订单列表（管理员权限）
     */
    @GetMapping("/all")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public Result<PageVO<Order>> getOrders(OrderQueryDTO query) {
        PageVO<Order> pageVO = orderService.getOrderList(query);
        return Result.success(pageVO);
    }

    /**
     * 更新订单状态（管理员权限）
     */
    @Operation(summary = "更新订单状态")
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public Result<Boolean> updateOrderStatus(
            @Parameter(description = "订单ID") @PathVariable("id") Long id,
            @Parameter(description = "订单状态：0-待支付，1-已支付，2-已发货，3-已完成，4-已取消") 
            @RequestParam Integer status) {
        Long userId = SecurityUtil.getCurrentUserId();
        boolean success = orderService.updateOrderStatus(userId, id, status);
        return success ? Result.success(true) : Result.error("更新订单状态失败");
    }
} 